using System;
using System.Collections.Generic;
using System.Text;
using System.Reflection;
using System.Data;

namespace ss_sdk
{
    public class Persistent : Attribute { }

    public class SSObject
    {
        public SSObject()
        {
            id = Guid.NewGuid();
        }
        private Guid id;
        [Persistent]
        public Guid Id
        {
            get { return id; }
        }

        public void Save()
        {
            string sql = string.Empty;
            string values = " (";
            sql = "INSERT INTO " + this.GetType().Name.ToUpper() + " (";

            int i = 0;
            Type tipo = this.GetType();

            List<Parameter> parametros = new List<Parameter>();

            foreach (SSPersistentProperty propriedade in GetPropertiesValue())
            {
                sql += propriedade.Property + ", ";
                values += "@p" + i.ToString() + ", ";
                parametros.Add(new Parameter("@p" + i.ToString(), propriedade.Value));
                i++;
            }
            sql = sql.Substring(0, sql.Length - 2);
            sql += ") VALUES ";
            values = values.Substring(0, values.Length - 2);
            values += ")";
            sql += values;
            Console.WriteLine(sql);
            foreach (Parameter p in parametros)
                Console.WriteLine(p.Value.ToString());
            IDbConnection cn = DataAcessLayer.Conexao();
            cn.Open();
            IDbCommand Cmd = DataAcessLayer.Comando(sql, parametros, cn, null);
            Console.WriteLine(sql);
            Cmd.ExecuteNonQuery();
            cn.Close();
        }

        public List<SSPersistentProperty> GetPropertiesValue()
        {
            List<SSPersistentProperty> lista = new List<SSPersistentProperty>();
            foreach (PropertyInfo prop in this.GetType().GetProperties())
            {
                foreach (Attribute atrib in Attribute.GetCustomAttributes(prop))
                {
                    if (atrib.GetType() == typeof(Persistent))
                        lista.Add(new SSPersistentProperty(prop.Name, prop.GetValue(this, null)));
                }
            }
            return lista;
        }
    }
}
